package Internet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    ServerSocket  serverSocket=null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("启动服务");
//        ExecutorService executorService= Executors.newCachedThreadPool();
        //只有在方法内部才可以写while
        while(true){
            Socket clientSocket=serverSocket.accept();
//            executorService.submit(()->{
//                try {
//                    processconnetion(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
            Thread t=new Thread(()->{
                try {
                    processconnetion(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            });
            t.start();

        }

    }

    private void processconnetion(Socket clientSocket) throws IOException {
        System.out.printf("客户端已上线,%s,%d\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()){
            //包装一下，为了方便输入与输出
            Scanner scanner=new Scanner(inputStream);
            PrintWriter printWriter=new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("客户端已经下线,%s,%d\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //1.读取请求
                String resquest=scanner.next();
                //2.计算请求，给出响应
                String response=process(resquest);
                //3.返回响应
                printWriter.println(response);
                //记得刷新缓冲区，使得数据可以及时从缓冲区中输出
                printWriter.flush();
                //4.打印日志
                System.out.printf("%s,%d,%s,%s\n",clientSocket.getInetAddress(),clientSocket.getPort()
                ,resquest,response);
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }
    }

    private String process(String resquest) {
        return resquest;
    }


    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer=new TcpEchoServer(9090);
        tcpEchoServer.start();

    }
}
